package com.asiainfo.sqlextractor.adapter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.calcite.linq4j.Enumerator;
import org.apache.calcite.util.Pair;

import java.util.List;

public class MemEnumerator implements Enumerator<Object[]> {

    private final TableDefine tableDefine;

    private final List<Pair<String, Class<?>>> columnTypes;

    private final JSONArray rows;

    private int index = -1;

    private Object[] currentRow;

    public MemEnumerator(TableDefine tableDefine, JSONArray rows) {
        this.tableDefine = tableDefine;
        this.columnTypes = tableDefine.columnTypes();
        this.rows = rows;
    }

    @Override
    public Object[] current() {
        return currentRow;
    }

    @Override
    public boolean moveNext() {
        index++;
        if (index < rows.size()) {
            setCurrentRow();
            return true;
        }
        return false;
    }

    private void setCurrentRow() {
        JSONObject row = rows.getJSONObject(index);
        this.currentRow = new Object[columnTypes.size()];
        for (int i = 0; i < columnTypes.size(); i++) {
            Pair<String, Class<?>> columnType = columnTypes.get(i);
            String name = columnType.left;
            Class<?> type = columnType.right;
            this.currentRow[i] = row.getObject(name, type);
        }
    }

    @Override
    public void reset() {
        index = -1;
        currentRow = null;
    }

    @Override
    public void close() {

    }

}